package com.idanchuang.support.mybatis.crypt.util;

import com.idanchuang.component.core.util.AbstractCryptUtil;
import com.idanchuang.support.mybatis.crypt.config.CryptConfigBean;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.time.LocalDateTime;
import java.util.HashSet;
import java.util.Set;

/**
 * 加解密工具类
 *
 * @author kamjin1996
 */
@SuppressWarnings("all")
public class CryptUtil extends AbstractCryptUtil {

    private static final Logger log = LoggerFactory.getLogger(CryptUtil.class);

    //-----------------------------------------IgnoreClass----------------------------------------------
    private static final Set<Class> IGNORE_CLASS = new HashSet<>();

    static {
        // initIgnoreClass
        IGNORE_CLASS.add(Byte.class);
        IGNORE_CLASS.add(Short.class);
        IGNORE_CLASS.add(Integer.class);
        IGNORE_CLASS.add(Long.class);
        IGNORE_CLASS.add(Float.class);
        IGNORE_CLASS.add(Double.class);
        IGNORE_CLASS.add(Boolean.class);
        IGNORE_CLASS.add(Character.class);
        IGNORE_CLASS.add(LocalDateTime.class);
    }

    public static boolean inIgnoreClass(Class cls) {
        return IGNORE_CLASS.contains(cls);
    }
    //-----------------------------------------IgnoreClass----------------------------------------------

    public static String encrypt(String sSrc) {
        return encrypt(sSrc, CryptConfigBean.getInstance().orElse(new CryptConfigBean()));
    }

    public static String encrypt(String sSrc, CryptConfigBean cryptConfigBean) {
        try {
            if (!cryptConfigBean.isEnableEncrypt()) {
                return sSrc;
            }
            return doEncrypt(sSrc, cryptConfigBean);
        } catch (Exception e) {
            log.info("encrypt str failed:[{}],rollback to source str:[{}]", e.getMessage(), sSrc);
        }
        return sSrc;
    }

    public static String decrypt(String sSrc) {
        return decrypt(sSrc, CryptConfigBean.getInstance().orElse(new CryptConfigBean()));
    }

    public static String decrypt(String sSrc, CryptConfigBean cryptConfigBean) {
        try {
            if (!cryptConfigBean.isEnableDecrypt()) {
                return sSrc;
            }
            return doDecrypt(sSrc, cryptConfigBean);
        } catch (Exception e) {
            log.info("decrypt str failed:[{}],rollback to source str:[{}]", e.getMessage(), sSrc);
        }
        return sSrc;
    }

}
